goog.provide('otq.initRoot');

goog.require('goog.dom');
goog.require('goog.dom.query');
goog.require('goog.editor.Command');
goog.require('goog.editor.Field');
goog.require('goog.editor.plugins.BasicTextFormatter');
goog.require('goog.editor.plugins.EnterHandler');
goog.require('goog.editor.plugins.HeaderFormatter');
goog.require('goog.editor.plugins.LinkBubble');
goog.require('goog.editor.plugins.LinkDialogPlugin');
goog.require('goog.editor.plugins.ListTabHandler');
goog.require('goog.editor.plugins.RemoveFormatting');
goog.require('goog.editor.plugins.SpacesTabHandler');
goog.require('goog.editor.plugins.UndoRedo');
goog.require('goog.json');
goog.require('goog.net.XhrIo');
goog.require('goog.ui.editor.DefaultToolbar');
goog.require('goog.ui.editor.ToolbarController');
goog.require('goog.ui.ToolbarToggleButton');
goog.require('goog.ui.ToolbarSeparator');

goog.require('otq.StayInListPlugin');

/**
 * @param {Element} elem The root objectives element.
 * @param {Element} toolbarElem Toolbar.
 * @constructor
 */
otq.list = function(elem, toolbarElem) {
	/** @type {Element} */
	this.streamRoot_ = elem;

	/** @type {Element} */
	this.toolbarElem_ = toolbarElem;

	var paths = document.location.pathname.match('/([^/]*)/([^/]*)');
	if (paths.length != 3) {
		throw "expected shortname/quarter in " + document.location.pathname;
	}

	/** @type {string} */
	this.shortname_ = paths[1];

	/** @type {string} */
	this.quarter_ = paths[2];

	this.editButton_ = new goog.ui.ToolbarToggleButton('Edit');
	this.editButton_.setTooltip('Edit objectives and key results.');
	this.scoreButton_ = new goog.ui.ToolbarToggleButton('Score');
	this.scoreButton_.setTooltip('Score objectives and key results.');
	this.editToolbar_ = new goog.ui.Toolbar();
	this.editToolbar_.addChild(this.editButton_, true);
	this.editToolbar_.addChild(new goog.ui.ToolbarSeparator(), true);
	this.editToolbar_.addChild(this.scoreButton_, true);
  this.field_ = new goog.editor.Field(this.streamRoot_.id);
};

otq.list.EDIT_BUTTONS = [
	goog.editor.Command.LINK,
	goog.editor.Command.UNDO,
	goog.editor.Command.REDO,
	goog.editor.Command.UNORDERED_LIST,
	goog.editor.Command.OUTDENT,
	goog.editor.Command.INDENT
];

otq.list.prototype.init = function() {
	this.editToolbar_.render(goog.dom.getElement(this.toolbarElem_, 'toolbar-edit'));

	var btf = new goog.editor.plugins.BasicTextFormatter();
	this.field_.registerPlugin(new otq.StayInListPlugin(btf));
  this.field_.registerPlugin(btf);
	this.field_.registerPlugin(new goog.editor.plugins.RemoveFormatting());
  this.field_.registerPlugin(new goog.editor.plugins.UndoRedo());
  this.field_.registerPlugin(new goog.editor.plugins.ListTabHandler());
  this.field_.registerPlugin(new goog.editor.plugins.SpacesTabHandler());
  this.field_.registerPlugin(new goog.editor.plugins.EnterHandler());
  this.field_.registerPlugin(new goog.editor.plugins.HeaderFormatter());
	this.field_.registerPlugin(new goog.editor.plugins.LinkDialogPlugin());
	this.field_.registerPlugin(new goog.editor.plugins.LinkBubble());

	this.fieldToolbar_ = goog.ui.editor.DefaultToolbar.makeToolbar(
			otq.list.EDIT_BUTTONS,
			goog.dom.getElement(this.toolbarElem_, 'toolbar-field'));
	this.fieldToolbar_.setVisible(false);
  var myToolbarController =
      new goog.ui.editor.ToolbarController(this.field_, this.fieldToolbar_);

  goog.events.listen(this.field_, goog.editor.Field.EventType.DELAYEDCHANGE,
			goog.bind(this.saveText_, this));
	//goog.events.listen(this.field_, goog.editor.Field.EventType.BEFORECHANGE,
	//		goog.bind(this.beforeChange_, this));
  goog.events.listen(this.editButton_, goog.events.EventType.CLICK,
			goog.bind(this.edit_, this));
	goog.events.listen(this.editButton_, goog.ui.Component.EventType.ACTION,
			goog.bind(this.edit_, this));
	goog.events.listen(this.scoreButton_, goog.events.EventType.CLICK,
			goog.bind(this.score_, this));
	goog.events.listen(this.scoreButton_, goog.ui.Component.EventType.ACTION,
			goog.bind(this.score_, this));
};

/**
 * Take whatever mess has appeared in the edit field and reduce it to a
 * list of lists. TODO(crawshaw): This function is tragic. Instead of
 * repairing the infinite mess possibly made with trogedit, consider
 * writing a custom editor.
 */
otq.list.prototype.radicalNormalization_ = function() {
	// TODO
};

otq.list.prototype.makeTextJson = function() {
	// TODO
	var obj = goog.dom.getElement('objectives').contentDocument.body.children[0];
	//var obj = document.getElementById('objectives').children[0].children[0];
	//var obj = this.streamRoot_.children[0];
	window.console.log(obj);
	if (obj.tagName != 'UL') {
		throw "expected: UL got: " + obj.tagName;
	}

	var children = [];
	var cur = null;
	for (var i = 0; i < obj.children.length; i++) {
		var c = obj.children[i];
		switch (c.tagName) {
			case 'LI':
				cur = { 'Text': c.innerText.trim() };
				children.push(cur);
				break;
			case 'UL':
				if (cur == null) {
					throw "expected some text";
				}
				var result = [];
				window.console.log(c);
				for (var j = 0; j < c.children.length; j++) {
					var res = c.children[j];
					if (res.tagName != 'LI') {
						continue;
					}
					result.push({ 'Text': res.innerText.trim() });
				}
				cur["Result"] = result;
				break;
			default: /* skip */
		}
	}
	return children;
};

otq.list.prototype.saveText_ = function() {
	this.radicalNormalization_();
	var obj = this.makeTextJson();
	var data = {
		"Shortname": this.shortname_,
		"Quarter": this.quarter_,
		"Objective": obj
	};
	window.console.log('save_:');
 	window.console.log(data);

	goog.net.XhrIo.send('/save', function(e) {
		var xhr = e.target;
		var obj = xhr.getResponseJson();
		window.console.log('save returned:');
	 	window.console.log(obj);
		if (!obj /* || obj.error */) {
			// TODO process error
			return;
		}
		// TODO proces success
	}, 'POST', goog.json.serialize(data));
};

otq.list.prototype.edit_ = function(e) {
	var ed = e.target.isChecked();
	this.fieldToolbar_.setVisible(ed);
	if (ed) {
		this.field_.makeEditable();
	} else {
		this.field_.makeUneditable();
	}
};

otq.list.prototype.score_ = function(e) {
	alert('Scoring: TODO');
};

otq.list.prototype.beforeChange_ = function(e) {
	//window.console.log('beforechange');
	//window.console.log(e);
};

otq.changeQuarter = function(qtr, e) {
	var shortname = document.location.pathname.match('/([^/]*)')[1];
	document.location.href = "/" + shortname + "/" + qtr;
};

otq.initRoot = function() {
	var list = new otq.list(
			document.getElementById('objectives'),
			document.getElementById('toolbar'));
	list.init();

	window.console.log('initRoot called');

	var qs = goog.dom.getElementsByClass('quarter');
	for (var i = 0; i < qs.length; i++) {
		var qtr = qs[i].id.substring(1);
		qs[i].onclick = goog.bind(
				otq.changeQuarter, qs[i], qtr);
	}
};

goog.exportSymbol('otq.initRoot', otq.initRoot);
